# -*- coding:utf-8 -*-
import getopt
import os
import shutil
import sys
from core import ReadFileClass, Report

rfc = ReadFileClass("config.yaml")
base_dir = os.path.dirname(os.path.abspath(__file__))
lib_dir = rfc.get_config("$.virtual_settings.lib_dir").current
# lib_dir = "/Users/metoto/VirtualEnv/apiAutoTest-v3/lib/python3.8/site-packages"
sys.path.append(base_dir)
sys.path.append(lib_dir)

from loguru import logger
from conftest import rfc
import pytest
import json
from core import ReadFileClass, DataProcess


def RunTest():
    #  --  TBD --
    # 1. 生成测试yaml文件（平台接入）
    # ReadFileClass.create_test_yaml_file()

    # 2. 命令行定义
    # 适配传参   project级测试-module级测试-case级测试
    # project  RunTest -p 'tcm'  or  RunTest -p 'inbox'
    # module   RunTest -m 'tcm/view' or RunTest -m 'inbox/interactions'
    # case     RunTest -c 'tcm/view/api/test_api_case_02.yaml'
    try:
        opts, args = getopt.getopt(sys.argv[1:], "hp:m:c:t:-e:")
    except getopt.GetoptError:
        print('ERROR! run.py -p <project> / -m <view> / -c <case> / -t <task> / -e <environment>')
        sys.exit(2)
    enable_env = ['web','email','assert_mode']
    email_flag = "0"
    web_flag = "0"
    for opt, arg in opts:
        if opt == '-h':
            print('run.py -p <project> / -m <view> / -c <case> / -t <task> / -e <environment>')
            sys.exit(2)
        elif opt in ("-p", "--project"):
            project = arg
            try:
                ReadFileClass.generate_cases(project, cmd_arg='p')
            except Exception as e:
                print("当前project路径输入有误")
                sys.exit(2)
            py_case_path = os.path.join(base_dir, rfc.get_config('$.file_path.case_folder').current, project)
        elif opt in ("-m", "--module"):
            module = arg
            try:
                ReadFileClass.generate_cases(module, cmd_arg="m")
            except Exception as e:
                print("当前module路径输入有误")
                sys.exit(2)
            py_case_path = os.path.join(base_dir, rfc.get_config('$.file_path.case_folder').current, module)
        elif opt in ("-c", "--case"):
            case = arg
            try:
                ReadFileClass.generate_cases(case, cmd_arg="c")
            except Exception as e:
                print("当前case路径输入有误")
                sys.exit(2)
            py_case_path = os.path.join(base_dir, rfc.get_config('$.file_path.case_folder').current, case).split(".")[
                               0] + ".py"
        elif opt in ("-t", "--task"):
            task = arg
            if isinstance(task, list):
                print("run.py -t <task>  eg. run.py -t ['test']")
                sys.exit(2)
            print("暂不支持此命令")
            sys.exit(2)
        elif opt in ("-e", "--environment"):
            # e.g. -e "email=1&web=0"
            environment_str = arg
            env_dict = DataProcess.handle_env(environment_str)
            if set(list(env_dict.keys()))<set(enable_env):
                if "email" in env_dict:
                    email_flag = env_dict["email"]
                if "web" in env_dict:
                    web_flag = env_dict["web"]
            else:
                print("当前暂不支持此环境变量")
                sys.exit(2)
    if len(opts) == 0:
        print("当前没有指定运行目录，选择全部执行")
        ReadFileClass.generate_cases('', cmd_arg="p")
        py_case_path = os.path.join(base_dir, rfc.get_config('$.file_path.case_folder').current, "")

    # 运行pytest脚本，指定运行目录
    # py_case_path = "/Users/metoto/VirtualEnv/apiAutoTest-v3/apiAutoTest-v3/case_script/smokeTest/"
    print("email_flag is ",email_flag)
    print("web_flag is ",web_flag)
    run(email=email_flag, web=web_flag, py_case_path=py_case_path)


def run(email = "0", web = "0", py_case_path: str = None):
    """
    启动测试
    :param email: 是否发送邮件
    :param web: 是否已服务形式打开报告（将忽略邮件服务）
    :return:
    """
    if os.path.exists("report/"):
        shutil.rmtree(path="report/")
    rfc.get_config("$.run_settings.assert_mode")
    # email=False
    # web=False
    # 解决 issues 句柄无效
    logger.remove()
    file_path = rfc.get_config("$.file_path").current
    logger.add(file_path["log"], enqueue=True, encoding="utf-8")
    logger.info(
        """
                 _    _         _      _____         _
  __ _ _ __ (_)  / \\  _   _| |_ __|_   _|__  ___| |_
 / _` | '_ \\| | / _ \\| | | | __/ _ \\| |/ _ \\/ __| __|
| (_| | |_) | |/ ___ \\ |_| | || (_) | |  __/\\__ \\ |_
 \\__,_| .__/|_/_/   \\_\\__,_|\\__\\___/|_|\\___||___/\\__|
      |_|
      Starting      ...     ...     ...
    """
    )

    # to-do
    # py_case_path = './case_script/tcm'
    # py_case_path = './case_script/record-lists/'
    pytest.main(args=["-vs", py_case_path, f"--alluredir={file_path['report']}/data"])
    # pytest.main(args=['--html=./TestReport.html'])

    if eval(web):
        # 自动以服务形式打开报告
        os.system(f'allure serve {file_path["report"]}/data')
    else:
        # 本地生成报告
        os.system(
            f'allure generate {file_path["report"]}/data -o {file_path["report"]}/html'
        )
        logger.success("报告已生成")

        # 保存报告图片
        Report.save_report_image()

        # 发送邮件
        if eval(email):
            from core import EmailServe

            EmailServe(rfc).serve()


if __name__ == "__main__":
    RunTest()
    # run(py_case_path="/Users/metoto/VirtualEnv/apiAutoTest-v3/apiAutoTest-v3/case_script/tcm/")
